import concurrent.futures
import time
import urllib.request
from urllib.error import URLError, HTTPError

# 定义一个网址列表
urls = ("https://www.cctv.com/",
        "https://www.baidu.com/hahaha.html",
        "https://www.gitee.com/",
        "https://www.github.com/",
        "https://www.baidu.com/abc")

def testThreadPoolExecutor():
    # 定义最大线程数量
    num_threads = 3

    futures = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=num_threads) as executor:
        for url in urls:
            # 提交任务到线程池
            try:
                future = executor.submit(urllib.request.urlopen, url, timeout=5)
                futures.append(future)
            except Exception as e:
                print(f"Error with URL {url}: {e.reason}")
        
        for future in concurrent.futures.as_completed(futures):
            try:
                data = future.result()
                if data.getcode() == 200:
                    print(f"OK  : {data.url} is reachable")
                else:
                    print(f"ERR : {data.url} is not reachable")
            except HTTPError as e:
                print(f"ERR : {e.code} {e.msg} {e.filename} ")
                continue
            except URLError as e:
                print(f"ERR : {e.filename} {e.reason}")
                continue
            except Exception as e:
                print(f"ERR : {e}")
                continue
        
    print("线程完成")


if __name__ == "__main__":
    testThreadPoolExecutor()